/*
 * @Author: FanWeiHua
 * @Date: 2021-05-14 17:31:19
 * @LastEditTime: 2021-07-26 14:36:24
 * @Description: webpack基础配置
 */
'use strict';
const path = require('path');
const rules = require('./common/Rules');
const optimization = require('./common/optimization');
const plugins = require('./common/plugins');
const webpack = require('webpack');
// 简化了HTML文件的创建，以便为你的webpack包提供服务
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 自动导入加载dll文件
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
/**
 * webpack的自定义配置
 */
const webpackConfig = JSON.parse(process.env.webpackConfig);
/**
 * 判断Dll优化策略存在
 */
const fs = require('fs');
let dllArr;
try {
  const mainfestPath = path.resolve(__dirname, '../dll/library/library.dll.manifest.json');
  fs.accessSync(mainfestPath);
  dllArr = [
    new webpack.DllReferencePlugin({
      context: path.resolve(__dirname, `../dist/${webpackConfig.project.name}`),
      manifest: mainfestPath
    }),
    /**
     * 自动导入加载dll文件
     */
    new AddAssetHtmlPlugin({
      filepath: path.resolve(__dirname, '../dll/library/*.js')
    })
  ];
} catch (err) {
  dllArr = [];
}
/**
 * 获取构建模式
 */
const getMode = {
  // 打包测试环境
  'prod-dev': 'development',
  // 开发环境
  dev: 'development',
  // 发布环境（可以不通过web容器直接访问）,注意：需要项目中的路由环境是hash才会支持
  local: 'development',
  // 发布环境
  prod: 'production'
};
/**
 * webpack的入口设置
 */
const entry = () => {
  let conList = [];
  if (process.env.NODE_ENV === 'dev') {
    conList = [
      'react-hot-loader/patch',
      'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
      webpackConfig.entry
    ];
  } else {
    conList = [webpackConfig.entry, path.resolve(__dirname, './common/logan.js')];
  }
  // 判断是否有日志服务
  if (webpackConfig.isLog) {
    conList.push(path.resolve(__dirname, './common/logan.js'));
  }
  return conList;
};
module.exports = () => {
  return {
    mode: getMode[process.env.NODE_ENV], // 配置webpack构建模式(development production)
    entry: entry(), // 入口,
    output: {
      path: path.resolve(__dirname, `../dist/${webpackConfig.project.name}`),
      filename: './static/js/[name]_[contenthash:16].js',
      chunkFilename: './static/js/chunk/chunk-[name]-[id].[chunkhash:8].bundle.js',
      publicPath: process.env.NODE_ENV === 'local' ? './' : webpackConfig.publicPath
    }, // 输出构建
    // module 关于模块配置
    module: {
      rules: rules() // rules 模块规则（配置 loader、解析器等选项）
    },
    plugins: plugins().concat([
      new HtmlWebpackPlugin({
        template: webpackConfig.templatePath,
        filename: 'index.html',
        inject: true,
        minify: false,
        chunksSortMode: 'auto'
      }),
      ...dllArr
    ]),
    // splitChunks分片
    optimization: optimization(),
    // 解析
    resolve: {
      extensions: ['.wasm', '.mjs', '.ts', '.tsx', '.js', '.json', '.jsx'], // 自动解析确定的扩展
      mainFiles: ['index', 'module'],
      alias: {
        '@': path.join(__dirname, '..', 'main'), // @映射到main目录
        '@project': path.join(__dirname, '..', 'main/project'), // @映射到main/project目录
        '@path': webpackConfig.project.path, // 当前项目地址别名
        'react-dom': '@hot-loader/react-dom' // 该包支持对React hook热更新
      }
    },
    stats: 'errors-only'
  };
};
